package com.px.controller;

import com.px.dto.ReturnResult;
import com.px.dto.ReturnResultUtils;
import com.px.pojo.ShUser;
import com.px.service.DxUserService;
import com.px.service.SmsService;
import com.px.utils.DtoUtil;
import com.px.utils.MD5Utils;
import com.px.utils.RedisUtils;
import com.px.vo.UserVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

import static org.bouncycastle.cms.RecipientId.password;

@RestController
public class DxUserController {
    @Resource
    private DxUserService dxUserService;
    @Resource
    private SmsService smsService;
    @Resource
    private RedisUtils redisUtils;

    //注册
    @PostMapping("/dxa")
    public ReturnResult tjsjh(UserVo user)throws Exception{
        //不要相信客户端传递的任何数据，有可能这个数据是违法的
        //验证客户端发送的手机号是否正确（服务端数据校验）
        //1、获取客户端发送的手机号
        String phone = user.getAccount();
        //2、正则表达式判断是否符合手机号的数据规则
        String phoneRegex="^1[3456789]\\d{9}$";
        if (StringUtils.isNotBlank(phone) && phone.matches(phoneRegex)){
            //3、判断手机号是否注册
            ShUser userByUserCode = dxUserService.cz(phone);
            if (userByUserCode != null) {
                return ReturnResultUtils.returnFail(2008, "该手机号已存在");
            }
            //4、生成验证码(4位数字验证码)
            String randomCode = String.valueOf(MD5Utils.getRandomCode());
            //5、发送短信    {1}:表示验证码 {2}表示有效期
            String[] datas = {randomCode,"5"};
            boolean result = smsService.sendMessage(phone, "1", datas);
            if (result){
                //6、保存验证码到reids
                String key = "activePhone："+phone;
                redisUtils.set(key,randomCode,60*10L);
                //7、保存用户信息到数据库里
                return dxUserService.tj(user);
            }else {
                return ReturnResultUtils.returnFail(2008,"短信发送失败，注册失败，注册失败");
            }
        }else {
            return ReturnResultUtils.returnFail(2008,"手机格式不正确");
        }
    }
}

